package com.rey.demo.api;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @ClassName: AsyncApi
 * @Description: TODO
 * @Author reyJojo
 * @Date 2021/12/3 12:59
 * @Version 1.0
 */
public class AsyncApi implements Watcher {
    private static ZooKeeper zooKeeper = null;

    private AsyncApi() {}

    public AsyncApi(String connectString, int sessionTimeout) throws IOException {
        System.out.println("创建客户端，并连接......");
        zooKeeper =  new ZooKeeper(connectString, sessionTimeout, new AsyncApi());
    }

    /**
     * 返回的event对象主要有两部分构成，keeperstate(状态)和eventtype（事件类型）,eventtype=none时session状态会发生改变
     */
    @Override
    public void process(WatchedEvent event) {
        System.out.println("获取到监听事件：" + event);
        if(event.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("正在处理相关业务......");
            doSomething();
        }
    }

    private void doSomething() {
        zooKeeper.create("/tasks/task-",
                "task".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT_SEQUENTIAL,
                new IStringCallBack(),
                "async");
    }

    static class IStringCallBack implements AsyncCallback.StringCallback {

        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    System.out.println("CONNECTIONLOSS");
                    break;
                case OK:
                    System.out.println("OK - {" + path + ", " + name + ", " + ctx + "}");
                    break;
                default:
                    System.out.println("DEFAULT");
                    break;
            }
        }

    }
    static class IVoidCallback implements AsyncCallback.VoidCallback {

        /**
         * processResult中rc代表返回编码（result code），常见的相应编码如下所示：
         *
         *     0（OK）：接口调用成功
         *     -4（CONNECTIONLOSS）：客户端与服务器断开
         *     -110（NODEEXISTS）：指定节点已存在
         *     -112（SESSIONEXPIRED）：会话过期
         */
        @Override
        public void processResult(int rc, String path, Object ctx) {
            // ......
        }

    }
}
